<?php

namespace app\admin\controller\subject;

use app\common\controller\Backend;

/**
 * 课程控制器
 */
class Subject extends Backend
{
    protected $model = null;
    protected $CategoryModel = null;
    protected $ChapterModel = null;

    // 关联查询
    protected $relationSearch = true;

    // 初始化
    public function _initialize()
    {
        parent::_initialize();

        $this->model = model('Subject.Subject');
        $this->CategoryModel = model('Subject.Category');
        $this->ChapterModel = model('Subject.Chapter');
    }

    // 首页
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);

        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->with(['category'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->count();

            $list = $this->model
                ->with(['category'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }

        return $this->view->fetch();
    }

    //添加
    public function add()
    {
        if ($this->request->isPost()) {
            //接收row前缀的数据，并接收为数组类型
            $params = $this->request->param('row/a');

            //组装数据
            $data = [
                'title' => $params['title'],
                'price' => $params['price'],
                'content' => $params['content'],
                'thumbs' => $params['thumbs'],
                'cateid' => $params['cateid'],
            ];

            //插入到数据库中
            $result = $this->model->validate('common/Subject/Subject')->save($data);

            if ($result === FALSE) {
                $this->error($this->model->getError());
                exit;
            } else {
                $this->success('添加课程成功');
                exit;
            }
        }

        //先将课程分类查询出来
        $catelist = $this->CategoryModel->column('id,name');
        $this->assign('catelist', build_select('row[cateid]', $catelist, [], ['class' => 'selectpicker', 'required' => '']));

        return $this->view->fetch();
    }

    // 编辑
    public function edit($ids = NULL)
    {
        //根据id要判断数据是否存在
        $row = $this->model->find($ids);

        //数据丢失，记录不存在
        if (!$row) {
            $this->error(__('No Results were found'));
            exit;
        }

        //判断是否有post过来请求
        if ($this->request->isPost()) {
            //接收row前缀请求参数，并返回一个数组类型
            $params = $this->request->param('row/a');

            //组装数据
            $data = [
                'id' => $ids,
                'title' => $params['title'],
                'content' => $params['content'],
                'price' => $params['price'],
                'cateid' => $params['cateid'],
                'thumbs' => $params['thumbs'],
            ];

            //直接去更新
            $result = $this->model->validate('common/Subject/Subject')->isUpdate(true)->save($data);

            if ($result === FALSE) {
                $this->error($this->model->getError());
                exit;
            }

            //判断是否有上传新图片 
            if ($data['thumbs'] != $row['thumbs']) {
                //不相等就说明有换图片了，就删除掉旧图片
                @is_file("." . $row['thumbs']) && @unlink("." . $row['thumbs']);
            }

            $this->success('编辑课程成功');
            exit;
        }

        //先将课程分类查询出来
        $catelist = $this->CategoryModel->column('id,name');
        $this->assign('catelist', build_select('row[cateid]', $catelist, $row['cateid'], ['class' => 'selectpicker', 'required' => '']));

        // 有数据要赋值到模板中去
        $this->assign('row', $row);

        //模板渲染
        return $this->view->fetch();
    }

    //软删除
    public function del($ids = NULL)
    {
        $list = $this->model->select($ids);

        //没有数据
        if (!$list) {
            $this->error(__('No Results were found'));
            exit;
        }

        //软删除
        $result = $this->model->destroy($ids);

        if ($result === FALSE) {
            $this->error('删除失败');
            exit;
        } else {
            $this->success('删除成功');
            exit;
        }
    }
}
